<?php
defined('BASEPATH') or exit('No direct script access allowed');
require APPPATH.'libraries/ApiController.php';
class Users extends ApiController
{
	public function __construct()
	{
	    parent::__construct();
	}
	function index(){
		 
	}
	
	
	public function list_by_page(){
		$token=123;//$this->verifyToken();
		if($token){
			$list=$user=$this->db->select("userid,username,nickname,mobile,enable,role,roleid,lastlogin")->get("auth_user")->result_array();
			$this->WRITE("code",1);
			$this->WRITE("list",$list);
			$this->WRITE("msg","success");
			$this->RESPONSE();
		}
		
	}
	
	public function login(){
		$data=$this->getKeys([
		  ['username',True,"账号"],
		  ['password',True,"密码"]
 		],'post');
		
		$user=$this->db->where("username",$data["username"])->get("auth_user")->row_array();
		if($user){
			if($user["password"]==$data["password"]){
				
				//token数据构建
				$token_arr=array(
				"userid"=>$user["userid"],
				"username"=>$user["username"],
				"nickname"=>$user["nickname"],
				"mobile"=>$user["mobile"]);
				
				//获取权限
				$rightids=$this->db->where("roleid",$user["roleid"])->get("auth_roles")->row_array()["permission"];
				$rights=$rightids==""? []:explode(",",$rightids);
				//有菜单
				$menus=[];
				if(count($rights)>0){
					$menus=$this->db->select("mid,title,pid,icon,enable,key,path,order")->where_in("mid",$rights)->get("auth_menu")->result_array();
				}
				$menus=$this->buildTree($menus,-1);
				
				$token=$this->createToken($token_arr);
				$this->db->where("userid",$user["userid"])->update("auth_user",array("token"=>$token));
				$data=array("userinfo"=>$token_arr,"token"=>$token,"menus"=>$menus);
				
				$this->WRITE("data",$data);
				$this->RESPONSE();
			}else{
				$this->WRITE("code",0);
				$this->WRITE("msg","账号或密码错误!");
				$this->RESPONSE();
			}
			
		}else{
			$this->WRITE("code",0);
			$this->WRITE("msg","账号或密码错误!");
			$this->RESPONSE();
		}
	}
	
	protected function buildTree($cats,$pid=-1){
		$tree=[];
		foreach($cats as $cat){
			if($cat["pid"]==$pid){
					$children=$this->buildTree($cats,$cat["mid"]);
					usort($children,function($a,$b){
						return $a["order"]<=$b["order"];
					});
					if($children){
						$cat["children"]=$children;
					}else{
						$cat["children"]=[];
					}
				$tree[]=$cat;
			}
		}
		usort($tree,function($a,$b){
			return $a["order"]<=$b["order"];
		});
		return $tree;
	} 
	
	
	
	
}